package com.nuts.base.interceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.util.StreamUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.nuts.base.core.MyException;
import com.nuts.base.core.annotation.SameUrlData;

/**
 * 一个用户 相同url 同时提交 相同数据 验证 主要通过 session中保存到的url 和 请求参数。如果和上次相同，则是重复提交表单
 * 
 * @author Administrator
 *
 */
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			SameUrlData annotation = method.getAnnotation(SameUrlData.class);
			if (annotation != null) {
				int outTime = annotation.outTime();
				if (repeatDataValidator(request, outTime)) {// 如果重复相同数据
					throw new MyException("操作过于频繁，请稍后再操作！");
				} else {
					return true;
				}
			}
			return true;
		} else {
			return super.preHandle(request, response, handler);
		}
	}

	/**
	 * 验证同一个url数据是否相同提交 ,相同返回true
	 * 
	 * @param httpServletRequest
	 * @return
	 * @throws IOException
	 */
	public boolean repeatDataValidator(HttpServletRequest httpServletRequest, int outTime) throws IOException {
		String params = "";
		String method = httpServletRequest.getMethod();
		if ("GET".equals(method)) {
			params = JSON.toJSONString(httpServletRequest.getParameterMap());
		} else if ("POST".equals(method)) {
			// 取出POST Body的数据
			byte[] bytes = StreamUtils.copyToByteArray(httpServletRequest.getInputStream());
			params = JSON.toJSONString(new String(bytes));
		} else {
			return false;
		}
		String url = httpServletRequest.getRequestURI();
		Map<String, String> map = new HashMap<String, String>();
		map.put(url, params);
		String nowUrlParams = map.toString();//
		HttpSession httpSession = httpServletRequest.getSession();
		httpSession.setMaxInactiveInterval(outTime); // outTime秒内不能重复提交
		Object preUrlParams = httpSession.getAttribute("repeatData");
		if (preUrlParams == null)// 如果上一个数据为null,表示还没有访问页面
		{
			httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
			return false;
		} else// 否则，已经访问过页面
		{
			if (preUrlParams.toString().equals(nowUrlParams))// 如果上次url+数据和本次url+数据相同，则表示重复添加数据
			{
				return true;
			} else// 如果上次 url+数据 和本次url加数据不同，则不是重复提交
			{
				httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
				return false;
			}

		}
	}

}
